import smtplib, requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from pathlib import Path
from .logger import get_logger
import requests, base64, hashlib, pathlib
import datetime

class Notifier:
    def __init__(self, cfg):
        self.log = get_logger("Notifier")
        self.smtp_cfg = cfg["smtp"]
        self.wx_hook = cfg["wechat"]["webhook"]
        self.token = cfg["pushplus"]["token"]
        self.wx_hook = cfg["wechat"]["webhook"]  # 从 config.yaml 读

    def send_mail(self, subject, body, attach=None):
        msg = MIMEMultipart()
        msg["From"] = self.smtp_cfg["user"]
        msg["To"] = msg["From"]
        msg["Subject"] = subject
        msg.attach(MIMEText(body, "plain", "utf-8"))
        if attach and Path(attach).exists():
            with open(attach, "rb") as f:
                att = MIMEText(f.read(), "base64", "utf-8")
                att["Content-Type"] = "application/octet-stream"
                att["Content-Disposition"] = f'attachment; filename="{Path(attach).name}"'
                msg.attach(att)
        with smtplib.SMTP_SSL(self.smtp_cfg["host"], self.smtp_cfg["port"]) as smtp:
            smtp.login(self.smtp_cfg["user"], self.smtp_cfg["pwd"])
            smtp.sendmail(msg["From"], msg["To"], msg.as_string())
        self.log.info("邮件已发送 to %s", self.smtp_cfg["user"])

    def send_wechat(self, title: str, content: str):
        ts = datetime.now().strftime("%m-%d %H:%M:%S")
        content = f"[{ts}] {content}"  # 时间前缀，避免短期重复
        url = "http://www.pushplus.plus/send"
        data = {
            "token": self.token,
            "title": title,
            "content": content,
            "template": "html"
        }
        r = requests.post(url, json=data, timeout=5)
        if r.json().get("code") != 200:
            raise RuntimeError("PushPlus 发送失败: " + r.text)

    def send_wechat_image(self, title: str, img_path: str):
        """
        企业微信机器人：发送本地图片
        """
        img_path = pathlib.Path(img_path)
        if not img_path.exists():
            raise FileNotFoundError(img_path)

        # 读取图片并计算 base64 + md5
        with open(img_path, "rb") as f:
            img_data = f.read()
        img_b64 = base64.b64encode(img_data).decode()
        img_md5 = hashlib.md5(img_data).hexdigest()

        payload = {
            "msgtype": "image",
            "image": {
                "base64": img_b64,
                "md5": img_md5
            }
        }

        resp = requests.post(self.wx_hook, json=payload, timeout=5)
        if resp.json().get("errcode") != 0:
            raise RuntimeError(f"企业微信推送失败：{resp.text}")